<template>
	<view class="login-type">
		<view class="logo">
			<rf-image :preview="false" :src="baseInfo.logo || logo"></rf-image>
		</view>
		<!--#ifdef H5-->
		<view>
			<button class="confirm-btn confirm-btn-bg" :disabled="btnLoading" :class="'text-' + themeColor.name" @tap="navTo('/pages/public/login')">
				已有账号登录
			</button>
			<button class="confirm-btn confirm-btn-bg" :disabled="btnLoading" :class="'text-' + themeColor.name" @tap="navTo(styleLoginType === 'one' ? `/pages/public/register` : `/pages/public/login?type=1`)">
				立即注册
			</button>
		</view>
		<!-- #endif -->
		<!--协议popup-->
		<rf-protocol-popup ref="mapState" @popupState="popupState" protocolPath="/pages/set/about/detail?field=protocol_register&title=注册协议"
		 policyPath="/pages/set/about/detail?field=protocol_privacy&title=隐私协议" v-if="isRfProtocolPopupShow"></rf-protocol-popup>
		<!-- 底部协议 -->
		<view class="footer-protocol">
			<text @tap="handleRfProtocolPopupShow" class="cuIcon" :class="appAgreementDefaultSelect ? `text-${themeColor.name} cuIcon-radiobox` : 'cuIcon-round'"></text>
			<text class="content">登录表示同意</text>
			<!-- 协议地址 -->
			<text :class="'text-' + themeColor.name" @tap="handleRfProtocolPopupShow">《{{appName}} 协议》</text>
		</view>
		<!-- 底部协议 -->

		<view class="footer" v-if="isAuthLoginShow && !closeThirdPartyLogin">
			<view class="d-header">
				<text>其他登录方式</text>
			</view>
			<view class="login-type-list">
				<button v-if="isAuthLoginShow" :disabled="btnLoading" :loading="btnLoading" class="login-type-btn" open-type="getUserInfo"
				 @tap="toAuthLogin">
					<image class="image" :src="wechat"></image>
				</button>
				<button :disabled="btnLoading" :loading="btnLoading" v-if="isIosAuthLoginShow" class="login-type-btn" open-type="getUserInfo"
				 @tap="toIosAuthLogin">
					<image class="image" :src="apple"></image>
				</button>
			</view>
		</view>
	</view>
</template>
<script>
	/**
	 * @des 登录类型
	 *
	 * @author 237524947@qq.com
	 * @date 2020-01-13 12:02
	 * @copyright 2019
	 */
	import {
		getOpenId,
		mpWechatLogin,
		appLogin,
		wechatH5Login,
		thirdPartyWechatOpenPlatform,
		thirdPartyApple,
		loginByCode
	} from '@/api/login';
	import rfProtocolPopup from '@/components/rf-protocol-popup';
	export default {
		components: {
			rfProtocolPopup
		},
		data() {
			return {
				btnLoading: false,
				isRfProtocolPopupShow: false, // 控制协议popup显示
				appAgreementDefaultSelect: this.$mSettingConfig.appAgreementDefaultSelect, // 是否允许点击登录按钮
				isAuthLoginShow: false,
				isIosAuthLoginShow: false,
				logo: this.$mSettingConfig.appLogo,
				baseInfo: {},
				appName: this.$mSettingConfig.appName,
				promoCodeParams: {},
				styleLoginType: this.$mSettingConfig.styleLoginType,
				wechat: this.$mAssetsPath.wechat,
				apple: this.$mAssetsPath.apple,
				closeThirdPartyLogin: this.$mSettingConfig.closeThirdPartyLogin,
				loginTypeList: [{
					text: '微信',
					icon: 'iconweixin'
				}]
			};
		},
		onShow() {
			this.btnLoading = false;
			/*  #ifdef H5  */
			var storeId = `${this.$mConfig.storeId}`;
			if (this.$mPayment.isWechat() && !this.$mStore.getters.hasLogin) {
				let code = this.getCode()

				if (this.code !== null && this.code !== "" && this.code !== undefined) {

					this.getOpenidAndUserinfo(this.code, storeId)
				}
			}
			/*  #endif  */
			if (uni.getStorageSync('accessToken')) {
				this.$mRouter.reLaunch({
					route: '/pages/index/index'
				});
			}
		},

		onLoad(options) {
			if (options && options.recommondCode) {
				uni.setStorageSync('recommondCode', options.recommondCode)
			}

			this.baseInfo = uni.getStorageSync('baseInfo')

			/*  #ifdef MP-WEIXIN */
			this.isAuthLoginShow = true;
			/*  #endif  */
			/*  #ifdef APP-PLUS */

			//if (uni.getSystemInfoSync().platform === 'ios') {
			this.isIosAuthLoginShow = true;
			//}
			/*  #endif  */
			// 如果不是第一次进来 就不需要强制阅读协议
			if (!uni.getStorageSync('notFirstTimeLogin')) {
				if (!this.appAgreementDefaultSelect) {
					this.appAgreementDefaultSelect = false;
				}
			} else {
				this.appAgreementDefaultSelect = true;
			}

		},
		methods: {
		// 授权登录
    			toAuthLogin() {
    				var storeId = `${this.$mConfig.storeId}`;
    				this.btnLoading = true;
    				if (!this.appAgreementDefaultSelect) {
    					this.$mHelper.toast('请阅读并同意协议', 1.5 * 1000);
    					this.btnLoading = false;
    					return;
    				}
    				const _this = this;

    				let authApi;
    				// #ifdef APP-PLUS
    				this.getuserinfoh5appwx(storeId);
    				// #endif
    				/*  #ifdef MP-WEIXIN */
    				uni.login({
    					provider: 'weixin',
    					success: function(loginRes) {
    						uni.getUserInfo({
    							provider: 'weixin',
    							success: function(infoRes) {
    								// sessionKey

    								let params = _this.promoCodeParams;
    								authApi = mpWechatLogin;
    								//	authApi = getOpenId;
    								params = { ...infoRes,
    									...params
    								};
    								params.code = loginRes.code;
    								params.storeId = storeId;
    								params.recommondCode = uni.getStorageSync('recommondCode');
    								_this.thirdPartyAuthLogin(authApi, params);
    							},
    							fail: function() {
    								_this.btnLoading = false;
    							}
    						});
    					},
    					fail: function() {
    						_this.btnLoading = false;
    						_this.$mHelper.log('暂不支持小程序登录');
    					}
    				});
    				/*  #endif  */
    			},
			// 通用跳转
			navTo(route) {
				if (!this.appAgreementDefaultSelect) {
					this.$mHelper.toast('请勾选并阅读协议，才能进行下一步哦', 1.5 * 1000);
					return;
				}
				this.$mRouter.redirectTo({
					route
				});
			},
			// 显示协议popup
			handleRfProtocolPopupShow() {
				this.isRfProtocolPopupShow = true;
			},
			// 监听是否同意协议
			popupState(e) {
				if (e) {
					this.appAgreementDefaultSelect = true;
					uni.setStorageSync('notFirstTimeLogin', true);
					this.isRfProtocolPopupShow = false;
				} else {
					this.appAgreementDefaultSelect = false;
					this.isRfProtocolPopupShow = false;
				}
			},
			getUrlParam(name) {
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
				let url = window.location.href.split('#')[0]
				let search = url.split('?')[1]
				if (search) {
					var r = search.substr(0).match(reg)
					if (r !== null) return unescape(r[2])
					return null
				} else {
					return null
				}
			},
			getuserinfoh5appwx() {
				var that = this;
				uni.login({
					success: res => {
						// res 对象格式

						uni.getUserInfo({
							success: info => {
								// 与服务器交互将数据提交到服务端数据库
								uni.request({
									url: `${appLogin}`,
									method: 'POST',
									header: {
										'content-type': 'application/x-www-form-urlencoded'
									},
									data: {
										sex: info.userInfo.gender,

										unionid: info.userInfo.openId,
										openid: info.userInfo.openId,
										nickname: info.userInfo.nickName,
										headimgurl: info.userInfo.avatarUrl
									},
									success: res => {

										// 登录成功 记录会员信息到本地
										if (res) {
											this.$mStore.commit('login', res);
											this.user_info = res.member;

											uni.switchTab({
												url: '/pages/index/index'
											});
										} else {
											uni.showToast({
												title: res.data
											});
										}
									},
									fail: e => {
										console.log(JSON.stringify(e));
									}
								});
							},
							fail: () => {
								uni.showToast({
									title: '微信登录授权失败'
								});
							}
						});
					},
					fail: () => {
						uni.showToast({
							title: '微信登录授权失败'
						});
						uni.hideLoading();
					}
				});
			},

			thirdPartyAuthLogin(authApi, params = {}) {
				const _this = this;
				_this.$http
					.post(authApi, params)
					.then(async r => {
						_this.btnLoading = false;
						if (!r.member.mobile) {
							console.log('1')
							this.$mStore.commit('login', r);
							_this.user_info = r.member;
							uni.showModal({
								content: '您尚未绑定账号，是否跳转登录页面？',
								success: confirmRes => {
									if (confirmRes.confirm) {
										uni.setStorageSync(
											'openId',
											JSON.stringify(_this.user_info.appletOpenId)
										);
										_this.$mRouter.push({
											route: '/pages/public/login'
										});
									}
								}
							});
						} else {
							console.log('11')
							await _this.$mStore.commit('login', r);
							_this.$mHelper.toast('已为您授权登录');
							const backToPage = uni.getStorageSync('backToPage');
							if (backToPage) {
								if (
									backToPage.indexOf('/pages/profile/profile') !== -1 ||
									backToPage.indexOf('/pages/cart/cart') !== -1 ||
									backToPage.indexOf('/pages/notify/notify') !== -1 ||
									backToPage.indexOf('/pages/index/index') !== -1 ||
									backToPage.indexOf('/pages/category/category') !== -1
								) {
									_this.$mRouter.reLaunch(JSON.parse(backToPage));
								} else {
									_this.$mRouter.redirectTo(JSON.parse(backToPage));
								}
								uni.removeStorageSync('backToPage');
								uni.removeStorageSync('wechatUserInfo');
							} else {
								_this.$mRouter.reLaunch({
									route: '/pages/profile/profile'
								});
							}
						}
					}).catch(() => {
						_this.btnLoading = false;
					});
			},
			// 获取code
			// 先判断url中有没有code，如果有code，表明已经授权，如果没有code，跳转微信授权链接
			getCode() {
				var appid = `${this.$mConfig.weixinAppId}`;
				var hostUrl = `${this.$mConfig.hostUrl}`;

				// 截取地址中的code，如果没有code就去微信授权，如果已经获取到code了就直接把code传给后台获取openId
				let code = this.getUrlCode('code')
				console.log('getCode' + code);

				if (code === null || code === '') {
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' +
						encodeURIComponent('https://mojin.51wangshi.com') +
						'&response_type=code&scope=snsapi_userinfo&state=1234#wechat_redirect'
					// redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code，这里需要用encodeURIComponent对链接进行处理。
					// 如果配置参数一一对应，那么此时已经通过回调地址刷新页面后，你就会再地址栏中看到code了。
					// http://127.0.0.1/pages/views/profile/login/login?code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
				}

			},

			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
					.replace(/\+/g, '%20')) || null
			},

			getOpenidAndUserinfo(code, storeId) {

				this.$http.get(`${wechatH5Login}`, {
					code: code,
					recommondCode: uni.getStorageSync('recommondCode'),
					storeId: storeId
				}).then(r => {
					this.$mStore.commit('login', r);
					this.$mRouter.reLaunch({
						route: '/pages/profile/profile'
					});
				});
			},
			// 苹果授权登录
			toIosAuthLogin() {
				this.btnLoading = true;
				if (!this.appAgreementDefaultSelect) {
					this.$mHelper.toast('请阅读并同意协议', 1.5 * 1000);
					this.btnLoading = false;
					return;
				}
				const _this = this;
				// eslint-disable-next-line
				plus.oauth.getServices(function(services) {
					let appleService;
					if (services && services.length) {
						for (let i = 0, len = services.length; i < len; i++) {
							if (services[i].id === 'apple') {
								appleService = services[i];
								break;
							}
						}
						if (!appleService) {
							_this.btnLoading = false;
							_this.$mHelper.toast('没有苹果登录授权服务');
							return;
						}
						appleService.login(e => {
							_this.$http
								.post(thirdPartyApple, {
									...e.target.appleInfo,
									..._this.promoCodeParams
								})
								.then(async r => {
									_this.btnLoading = false;
									if (!r.login) {
										_this.user_info = r.user_info;
										uni.showModal({
											content: '您尚未绑定账号，是否跳转登录页面？',
											success: confirmRes => {
												if (confirmRes.confirm) {
													uni.setStorageSync(
														'wechatUserInfo',
														JSON.stringify(_this.user_info)
													);
													uni.setStorageSync('oauthClient', 'iOS');
													_this.$mRouter.push({
														route: '/pages/public/login'
													});
												}
											}
										});
									} else {
										await _this.$mStore.commit('login', r.user_info);
										_this.$mHelper.toast('已为您授权登录');
										const backToPage = uni.getStorageSync('backToPage');
										if (backToPage) {
											if (
												backToPage.indexOf('/pages/profile/profile') !== -1 ||
												backToPage.indexOf('/pages/cart/cart') !== -1 ||
												backToPage.indexOf('/pages/notify/notify') !== -1 ||
												backToPage.indexOf('/pages/index/index') !== -1 ||
												backToPage.indexOf('/pages/category/category') !== -1
											) {
												_this.$mRouter.reLaunch(JSON.parse(backToPage));
											} else {
												_this.$mRouter.redirectTo(JSON.parse(backToPage));
											}
											uni.removeStorageSync('backToPage');
											uni.removeStorageSync('wechatUserInfo');
										} else {
											_this.$mRouter.reLaunch({
												route: '/pages/profile/profile'
											});
										}
									}
								}).catch(() => {
									_this.btnLoading = false;
								});
						}, function() {
							// 获取 services 失败
							_this.btnLoading = false;
						});
					}
				}, function() {
					// 获取 services 失败
					_this.btnLoading = false;
				});

			}
		}
	};
</script>
<style lang="scss">
	page {
		background: #fff;
		height: calc(100% - 88upx);
	}

	.login-type {
		padding-top: 80upx;

		.logo {
			text-align: center;
			margin-bottom: 80upx;

			image {
				width: 180upx;
				height: 180upx;
				border-radius: 28upx;
			}
		}

		.confirm-btn {
			width: 84%;
			margin: 0 7% 50upx;
			height: 84upx;
			line-height: 84upx;
			font-size: $font-lg;
			border: 1upx solid;
		}

		.confirm-btn-bg {
			background: none;
		}

		.footer {
			width: 100%;
			text-align: center;
			position: fixed;
			bottom: 40upx;
			font-size: $font-sm + 2upx;

			.protocol {
				color: $base-color;
				margin: 0 10upx;
			}

			.d-header {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 80upx;
				margin-bottom: $spacing-base;
				font-size: $font-base + 2upx;
				color: $font-color-base;
				position: relative;

				text {
					padding: 0 $spacing-lg;
					background: #fff;
					position: relative;
					z-index: 1;
				}

				&:after {
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translateX(-50%);
					width: 300upx;
					height: 0;
					content: '';
					border-bottom: 1px solid #ccc;
				}
			}

			.login-type-list {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;

				.login-type-btn {
					border: none;
					background: none;
					padding: 0 40upx 0 0;
					margin: 0;

					.image {
						width: 64upx;
						height: 64upx;
					}

					&:after {
						border: none;
					}
				}

				.iconfont {
					font-size: 50upx;
					color: $font-color-base;
				}
			}
		}
	}
</style>
